library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(shiny)
## This version of Shiny is designed to work with 'htmlwidgets' >= 1.5.
##     Please upgrade via install.packages('htmlwidgets').
library(tidyverse)
## ── Attaching packages ──────────────────────────── tidyverse 1.2.1 ──
## ✔ tibble  2.1.3     ✔ purrr   0.3.2
## ✔ tidyr   1.0.0     ✔ dplyr   0.8.3
## ✔ readr   1.3.1     ✔ stringr 1.4.0
## ✔ tibble  2.1.3     ✔ forcats 0.4.0
## ── Conflicts ─────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks plotly::filter(), stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(rworldmap)
## Loading required package: sp
## ### Welcome to rworldmap ###
## For a short introduction type :   vignette('rworldmap')
library(arsenal)
library(leaflet)
library(rworldmap) 
library(countrycode)  # Gets country code 
library(viridis)
## Loading required package: viridisLite

firstly draw every years map

happy = read_csv("data/final_data.csv") %>% 
  janitor::clean_names() %>% 
  select(-long,-lat) %>% 
  unique %>% 
  mutate(label = str_c("<b>Happiness: ", round(life_ladder,2), 
                      "</b><br>Country : ", country_name,
                      sep = ""),
        code = countrycode(country_name, 'country.name', 'iso3c'),## match code
        code = replace_na(code,"XKX"))
## Parsed with column specification:
## cols(
##   country_name = col_character(),
##   year = col_double(),
##   life_ladder = col_double(),
##   log_gdp_per_capita = col_double(),
##   social_support = col_double(),
##   healthy_life_expectancy_at_birth = col_double(),
##   freedom_to_make_life_choices = col_double(),
##   positive_affect = col_double(),
##   negative_affect = col_double(),
##   generosity = col_double(),
##   perceptions_of_corruption = col_double(),
##   long = col_double(),
##   lat = col_double()
## )
## Warning in countrycode(country_name, "country.name", "iso3c"): Some values were not matched unambiguously: Kosovo

with long and lat, how to map in plotly?

  1. not long and lat but world choroplath

plot the map according to year. Try to make it a function taking year as argument.

# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)

# specify map projection/options
g <- list(
  showframe = FALSE,
  showcoastlines = FALSE,
  projection = list(type = 'Mercator')
)

## making map according to year

global_happy_year <- function(i){
  happy_yeari = happy %>% 
    filter(year == i)
  p <- plot_geo(happy_yeari) %>%
  add_trace(
    z = ~life_ladder, color = ~life_ladder, colors = 'Blues',
    text = ~label, locations = ~code, marker = list(line = l)
  ) %>%
  colorbar(title = 'Happiness index') %>%
  layout(
    title = paste(as.character(i), "Global Happiness Index"),
    geo = g
  )
  return(p)
}

global_happy_year(2018)
global_happy_year(2017)
global_happy_year(2016)
global_happy_year(2011)

create a link? # Create a shareable link to your chart # Set up API credentials: https://plot.ly/r/getting-started chart_link = api_create(p, filename=“choropleth-world”) chart_link

  1. with long and lat? necessary?

Secondly, try to add movable bar.

  1. can we substitute this movie histogrom to our plot?
ui <- shinyUI(fluidPage(
  titlePanel("Years"),
  sidebarPanel(
    sliderInput("year", "Year:", min = 2011, max = 2018, value = 1)
  ),
  mainPanel(
    plotlyOutput("trendPlot")
  )
))


## instead with world map 

server <- shinyServer(function(input, output) {

  output$trendPlot <- renderPlotly({

    ##plot function
    p <- global_happy_year(input$year)
    # style the xaxis
    layout(p)
  })
})
shinyApp(ui, server)
## 
## Listening on http://127.0.0.1:3845

try to add gif(zhazha shuyi)

library(magick)
## Linking to ImageMagick 6.9.9.39
## Enabled features: cairo, fontconfig, freetype, lcms, pango, rsvg, webp
## Disabled features: fftw, ghostscript, x11
library(animation)
library(rbokeh)
## Registered S3 method overwritten by 'pryr':
##   method      from
##   print.bytes Rcpp
library(htmlwidgets)
library(mapview)
library(webshot)
library(processx)
library(listviewer)

saveWidget(global_happy_year(2011),file = "m2011.html")
saveWidget(global_happy_year(2016),file = "m2016.html")
saveWidget(global_happy_year(2017),file = "m2017.html")
saveWidget(global_happy_year(2018),file = "m2018.html")

webshot::install_phantomjs()
## phantomjs has been installed to /Users/sfdsfswerw/Library/Application Support/PhantomJS
webshot(url = "m2011.html",file = "data/m2011.jpg",vwidth = 990,
  vheight = 750)

webshot(url = "m2016.html",file = "data/m2016.jpg",vwidth = 992,
  vheight = 744)

webshot(url = "m2017.html",file = "data/m2017.jpg",vwidth = 992,
  vheight = 744)

webshot(url = "m2018.html",file = "data/m2018.jpg",vwidth = 990,
        vheight = 750)

map_2018 = global_happy_year(2018)
map_2017 = global_happy_year(2017)
map_2016 = global_happy_year(2016)
map_2011 = global_happy_year(2011)

list.files(path = "data/",pattern = "*.jpeg",full.names = T) %>% 
  map(image_read) %>% 
  image_join() %>% 
  image_animate(fps=2)